import "dart:convert";
import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/apartment/check_in/index.dart";
import "package:ct_pa_majordomo/pages/pre_check_in/api.dart";
import "package:ct_pa_majordomo/pages/pre_check_in/audit/index.dart";
import "package:ct_pa_majordomo/pages/pre_check_in/edit/index.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/empty_data/index.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/filter_dropdown.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/filter_header.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/index.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:ct_pa_majordomo/widgets/tai_dialog/index.dart";
import "package:ct_pa_majordomo/widgets/bottom_sheet/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:ct_pa_majordomo/pages/pre_check_in/utils/status.dart";
import "package:nfc_manager/nfc_manager.dart";

class PreCheckIn extends StatefulWidget {
  const PreCheckIn({super.key});

  @override
  State<StatefulWidget> createState() => _PreCheckInState();
}

class _PreCheckInState extends State<PreCheckIn> {
  final ScrollController _scrollController = ScrollController();
  List _list = [];
  bool _isLoading = false;
  Map<String, dynamic> _params = {"pageSize": 20, "pageNum": 1, "status": ""};
  final List _statusList = PreCheckInStatus.statusList;
  int _total = 0;

  final List<FilterHeaderItem> _headerItems = [
    FilterHeaderItem(title: "状态"),
    FilterHeaderItem(
      title: "数量：0",
      render: (title) {
        return Text(
          title,
          textAlign: TextAlign.center,
          style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
        );
      },
    ),
  ];

  Future<void> _getPreCheckInList() async {
    try {
      _isLoading = true;
      Map resData = await preCheckInApi.getPreCheckInList(_params);
      _isLoading = false;
      setState(() {
        _total = resData["total"] ?? 0;
        _list = resData["rows"] ?? [];
        _headerItems[1].title = "数量：$_total";
      });
    } catch (error) {
      print(error);
    }
  }

  Future<void> _refresh() async {
    _total = 0;
    _list = [];
    _params["pageNum"] = 1;
    await _getPreCheckInList();
  }

  void _onScroll() {
    if (_isLoading || _list.length >= _total) return;
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      setState(() {
        _params["pageNum"] += 1;
        _getPreCheckInList();
      });
    }
  }

  // 获取房间显示名称
  String _getRoomDisplayName(Map item) {
    try {
      if (item["room"] != null) {
        String name = item["room"]["name"] ?? "";
        String buildingName = item["room"]["buildingName"] ?? "";
        String fullName = "$buildingName$name";
        return fullName.isNotEmpty ? fullName : "暂未登记房间";
      }
      return "暂未登记房间";
    } catch (e) {
      return "暂未登记房间";
    }
  }

  // 选择房间
  void _selectRoom(Map item) async {
    if (item["roomId"] != -1) {
      Map resData = await apartmentApi.getRoomInfo(item["roomId"]);
      Map room = resData["data"] ?? {};
      Stacker.pushNamed(Keys.PRE_CHECK_IN_CHECK_IN, arguments: {
          "registerId": item["registerId"],
          "room": room,
        }).then((value) {
          if (value != null && value == true) {
            _refresh();
          }
        });
        return;
    }
    Map resData = await apartmentApi.getEmptyRoomList({
      "pageNum": 1,
      "pageSize": 999,
    });
    List rooms = resData["rows"] ?? [];
    print(rooms);
    if (context.mounted) {
      Map? popped = await showRoundedBottomSheet(
        builder: (context) => BottomSheetSelect(
          items: rooms,
          compare: (item) => item["roomId"] == item["roomId"],
          itemAsString: (item) => "${item["buildingName"]} ${item["name"]}",
        ),
      );
      if (popped != null) {
        Stacker.pushNamed(Keys.PRE_CHECK_IN_CHECK_IN, arguments: {
          "registerId": item["registerId"],
          "room": popped,
        }).then((value) {
          if (value != null && value == true) {
            _refresh();
          }
        });
      }
    }
  }

  @override
  void initState() {
    _scrollController.addListener(_onScroll);
    _getPreCheckInList();
    super.initState();
  }

  @override
  void dispose() {
    _scrollController.removeListener(_onScroll);
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "预登记",
      floatingActionButton: Container(
        margin: const EdgeInsets.only(bottom: 50, right: 16),
        child: FloatingActionButton(
          backgroundColor: ThemeVars.colorPrimary,
          onPressed: () {
            Navigator.push(
              context,
              CupertinoPageRoute(
                builder: (BuildContext context) {
                  return const PreCheckInEdit();
                },
              ),
            ).then((value) {
              if (value == true) {
                _refresh();
              }
            });
          },
          shape: const CircleBorder(),
          child: const Icon(Icons.add, color: Colors.white),
        ),
      ),
      child: FilterLayout(
        headerItems: _headerItems,
        dropdownItems: [
          FilterDropdownItem(
            items: _statusList,
            itemAsString: (item) => item["name"],
            compare: (item) => item["value"] == _params["status"],
            onChanged: (item) {
              setState(() {
                _params["status"] = item["value"];
                _headerItems[0].title = item["name"];
                _refresh();
              });
            },
          ),
        ],
        child: RefreshIndicator(
          onRefresh: _refresh,
          child: _list.isEmpty
              ? const EmptyData()
              : ListView.separated(
                  controller: _scrollController,
                  padding: const EdgeInsets.all(ThemeVars.paddingPage),
                  itemBuilder: (context, index) {
                    Map item = _list[index];
                    Map mainRenter = item["renterList"].firstWhere((renter) => renter["mainFlag"] == "1");
                    return Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          Navigator.push(
                            context,
                            CupertinoPageRoute(
                              builder: (BuildContext context) {
                                return PreCheckInAudit(
                                  registerId: int.parse(item["registerId"].toString()),
                                  isAudit: false,
                                );
                              },
                            ),
                          );
                        },
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  mainRenter["name"] ?? "--",
                                  style: const TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                PreCheckInStatus.buildStatusTag(item["status"]),
                              ],
                            ),
                            const SizedBox(height: 8),
                            Text("联系方式：${mainRenter["contacts"]}"),
                            const SizedBox(height: 4),
                            Text("登记时间：${DateTools.formatYMD(item["createTime"], format: '{y}-{m}-{d} {h}:{i}:{s}')}"),
                            const SizedBox(height: 4),
                            Text("房间：${_getRoomDisplayName(item)}"),
                            const SizedBox(height: 4),
                            if (item["status"] == "2") ...[
                              const SizedBox(height: 4),
                              Text(
                                "驳回原因：${item["rejectReason"]}",
                                style: const TextStyle(color: ThemeVars.colorError),
                              ),
                            ],
                            // 只有当有操作时才显示操作栏
                            if (item["status"] == PreCheckInStatus.PENDING || item["status"] == PreCheckInStatus.APPROVED) ...[
                              const SizedBox(height: 12),
                              const Divider(height: 1, thickness: 0.5, color: ThemeVars.colorDivider),
                              const SizedBox(height: 12),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  if (item["status"] == PreCheckInStatus.PENDING || item["status"] == PreCheckInStatus.APPROVED) ...[
                                    InkWell(
                                      onTap: () {
                                        Navigator.push(
                                          context,
                                          CupertinoPageRoute(
                                            builder: (BuildContext context) {
                                              return PreCheckInEdit(
                                                registerId: int.parse(item["registerId"].toString()),
                                              );
                                            },
                                          ),
                                        ).then((value) {
                                          if (value == true) {
                                            _refresh();
                                          }
                                        });
                                      },
                                      child: const Padding(
                                        padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                                        child: Text("修改", style: TextStyle(
                                          fontSize: 14,
                                          color: ThemeVars.colorPrimary,
                                        )),
                                      ),
                                    ),
                                    if (item["status"] == PreCheckInStatus.PENDING)
                                      const Text("|", style: TextStyle(color: ThemeVars.colorDivider)),
                                  ],
                                  if (item["status"] == PreCheckInStatus.PENDING) ...[
                                    InkWell(
                                      onTap: () {
                                        Navigator.push(
                                          context,
                                          CupertinoPageRoute(
                                            builder: (BuildContext context) {
                                              return PreCheckInAudit(
                                                registerId: int.parse(item["registerId"].toString()),
                                                isAudit: true,
                                              );
                                            },
                                          ),
                                        ).then((value) {
                                          if (value == true) {
                                            _refresh();
                                          }
                                        });
                                      },
                                      child: const Padding(
                                        padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                                        child: Text("审核", style: TextStyle(
                                          fontSize: 14,
                                          color: ThemeVars.colorPrimary,
                                        )),
                                      ),
                                    ),
                                  ],
                                  if (item["status"] == PreCheckInStatus.APPROVED) ...[
                                    const Text("|", style: TextStyle(color: ThemeVars.colorDivider)),
                                    InkWell(
                                      onTap: () => _selectRoom(item),
                                      child: const Padding(
                                        padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                                        child: Text("办理入住", style: TextStyle(
                                          fontSize: 14,
                                          color: ThemeVars.colorPrimary,
                                        )),
                                      ),
                                    ),
                                  ],
                                  if (item["status"] == PreCheckInStatus.CHECKED_IN) ...[
                                    InkWell(
                                      onTap: () async {
                                        bool isActive = await NfcManager.instance.isAvailable();
                                        if (isActive) {
                                          NfcManager.instance.startSession(onDiscovered: (NfcTag tag) async {
                                            print(tag.data.toString());
                                          });
                                        } else {
                                          print("不得行>>>>>>>>>>>>>");
                                        }
                                      },
                                      child: const Padding(
                                        padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                                        child: Text("发卡", style: TextStyle(
                                          fontSize: 14,
                                          color: ThemeVars.colorPrimary,
                                        )),
                                      ),
                                    ),
                                  ],
                                ],
                              ),
                            ],
                          ],
                        ),
                      ),
                    );
                  },
                  separatorBuilder: (context, index) =>
                      const SizedBox(height: 12),
                  itemCount: _list.length,
                ),
        ),
      ),
    );
  }
}
